package com.zpark.security.distributed.order.controller;

import com.zpark.security.distributed.order.model.UserDTO;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @PackageName: com.zpark.security.distributed.order.controller
 * @ClassName: OrderController
 * @Description:
 * @author: RZS
 * @date: 2021/8/9  9:40
 */
@RestController
public class OrderController {

    // 该注解表示拥有p1权限者才可以访问此url映射的方法
    @PreAuthorize("hasAuthority('p1')")
    @GetMapping(value = "/r1")
    public String r1(){
        //获取用户身份信息
        UserDTO  userDTO = (UserDTO)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return userDTO.getUsername() + "访问资源1";
    }

    @PreAuthorize("hasAuthority('p2')")
    @GetMapping(value = "/r2")
    public String r2(){//通过Spring Security API获取当前登录用户
        UserDTO user =
                (UserDTO)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        return user.getUsername() + "访问资源2";
    }
}
